﻿Imports System.IO
Imports System.Xml.Serialization

Public Class Serialization

    REM 反序列化文件
    Public Shared Function Load(ByVal type As Type, ByVal filename As String) As Object
        Dim fs As FileStream = Nothing
        Try
            fs = New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            Dim serializer As XmlSerializer = New XmlSerializer(type)
            Return serializer.Deserialize(fs)
        Catch ex As Exception
            Throw ex
        Finally
            If Not fs Is Nothing Then
                fs.Close()
            End If
        End Try

    End Function

    REM 序列化文件
    Public Shared Function Save(ByVal obj As Object, ByVal filename As String) As Boolean
        Dim success As Boolean = False
        Dim fs As FileStream = Nothing
        Try
            fs = New FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)
            Dim serializer As XmlSerializer = New XmlSerializer(obj.GetType())
            serializer.Serialize(fs, obj)
            success = True
        Catch ex As Exception
            Throw ex
        Finally
            If Not fs Is Nothing Then
                fs.Close()
            End If
        End Try
        Return success
    End Function

    REM 序列化成字符串
    Public Shared Function Serialize(ByVal obj As Object) As String
        Dim returnStr As String = String.Empty

        Dim serializer As XmlSerializer = New XmlSerializer(obj.GetType())
        Dim ms As MemoryStream = New MemoryStream()
        Dim xtw As System.Xml.XmlTextWriter = Nothing
        Dim sr As StreamReader = Nothing
        Try
            xtw = New System.Xml.XmlTextWriter(ms, System.Text.Encoding.UTF8)
            xtw.Formatting = System.Xml.Formatting.Indented
            serializer.Serialize(xtw, obj)
            ms.Seek(0, SeekOrigin.Begin)
            sr = New StreamReader(ms)
            returnStr = sr.ReadToEnd()
        Catch ex As Exception
            Throw ex
        Finally
            If Not xtw Is Nothing Then xtw.Close()
            If Not sr Is Nothing Then sr.Close()
            ms.Close()
        End Try
        Return returnStr
    End Function

    REM 反序列化成对象
    Public Shared Function DeSerialize(ByVal type As Type, ByVal s As String) As Object
        Dim b As Byte() = System.Text.Encoding.UTF8.GetBytes(s)
        Try
            Dim serializer As XmlSerializer = New XmlSerializer(type)
            Return serializer.Deserialize(New MemoryStream(b))
        Catch ex As Exception
            Throw ex
        End Try

    End Function

End Class
